/**
 * <pre>
 * Title: 		SessionController.java
 * Author:		linriqing
 * Create:	 	2010-6-3 上午10:34:51
 * Copyright: 	Copyright (c) 2010
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.itfinoss.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.hengpeng.common.acl.SubSystemConfig;
import com.hengpeng.common.acl.impl.PermissionProviderImpl;
import com.hengpeng.common.acl.vo.Passport;
import com.hengpeng.common.acl.vo.Permission;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.persist.ClientContextHolder;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.util.MD5;
import com.hengpeng.common.web.core.RandomImageServlet;
import com.hengpeng.itfinbase.persist.AppRole;
import com.hengpeng.itfinbase.persist.AppUser;
import com.hengpeng.itfinbase.persist.PermissionPo;
import com.hengpeng.itfinoss.constant.Constants;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.util.BeanClone;

/**
 * <pre>
 * 会话控制器
 * </pre>
 * @author linriqing
 * @version 1.0, 2010-6-3
 */
@Controller
@RequestMapping(value = "/session")
@SessionAttributes( { Constant.PROFILE_SESSION_NAME, Constants.ClientConstants.USER_SESSION_KEY })
public class SessionController extends BaseController
{
	@Autowired
	private ServiceFactory serviceFactory;

	private static final Log logger = LogFactory.getLog(SessionController.class);

	@RequestMapping(method = RequestMethod.POST)
	@ModelAttribute(Constant.PROFILE_SESSION_NAME)
	public ModelAndView create(Passport passport, ModelMap modelMap, @RequestParam("confirmCode") String confirmCode,
			HttpServletRequest request) {
		logger.info("创建新会话:" + passport.getUserId());
		if (RandomImageServlet.checkSessionConfirmCode(request, confirmCode)) {
			DynamicQuery query = new DynamicQuery(AppUser.class);
			query.eq("loginName", passport.getUserId());
			query.eq("password", MD5.encodeString(passport.getSecretKey(), "utf-8"));
			query.setQueryType(QueryType.JDBC);
			List<AppUser> findByNamedQuery = serviceFactory.getPersistService().find(AppUser.class, query);
			if (findByNamedQuery != null && findByNamedQuery.size() > 0) {
				AppUser user = findByNamedQuery.get(0);
				if(AppUser.UserStatus.CLOSE.equals(user.getState())  || AppUser.UserStatus.STOP.equals(user.getState())) {
					return new ModelAndView(new RedirectView("/", true));
				}
				Passport profile = new Passport();
				profile.setNickName(user.getNickName());
				profile.setRealName(user.getRealName());
				profile.setLastLogin(user.getLastLogin());
				profile.setSerialNo(user.getUserNo());
				profile.setUserId(user.getLoginName());
				profile.setToken(user.getToken());
				profile.setSecretKey(user.getPassword());
				if (user.getLoginName().equals("admin")) {
					profile.setRoleName("超级管理员");
					Collection<SubSystemConfig> subSystems = PermissionProviderImpl.getInstance().getSubSystems();
					Set<Permission> permissions = new HashSet<Permission>();
					for (SubSystemConfig subSystemConfig : subSystems) {
						permissions.addAll(PermissionProviderImpl.getInstance().getAllPermissionBySubSystem(subSystemConfig.getName()));
					}
					profile.setPermissions(permissions);
					modelMap.addAttribute(Constant.PROFILE_SESSION_NAME, profile);
					modelMap.addAttribute(Constants.ClientConstants.USER_SESSION_KEY, user);
					ClientContextHolder.setClientAction(profile);
				} else {
					Set<AppRole> roles = user.getRoles();
					Set<Permission> permissions = new HashSet<Permission>();
					for (AppRole appRole : roles) {
						List<PermissionPo> polist = new ArrayList<PermissionPo>(appRole.getPermission());
						List<Permission> list = BeanClone.clone(polist, Permission.class);
						permissions.addAll(list);
					}
					if (roles.size() > 0) {
						profile.setRoleName(roles.iterator().next().getName());
					}
					profile.setPermissions(permissions);
					modelMap.addAttribute(Constant.PROFILE_SESSION_NAME, profile);
					modelMap.addAttribute(Constants.ClientConstants.USER_SESSION_KEY, user);
					ClientContextHolder.setClientAction(profile);
				}
				user.setLastLogin(new Date());
				user.setLastUpdate(new Date());
				serviceFactory.getPersistService().update(user);
//				EventContextImpl.getInstance().perform(
//						new AdminOperateEvent(this, user.getLoginName() + "登录成功", ActionState.Ended,
//								AdminOperateType.Login, profile));
				logger.info("创建新会话成功:" + passport.getUserId());

				ModelAndView modelAndView = new ModelAndView("/common/welcome");
				modelAndView.addObject("passport", passport);
				return modelAndView;
			} else {
				return new ModelAndView(new RedirectView("/", true));
			}
		} else {
			return new ModelAndView(new RedirectView("/", true));
		}
	}

	@RequestMapping(value = "delete", method = RequestMethod.GET)
	public ModelAndView delete(ModelMap modelMap)
	{
		Passport passport = (Passport) modelMap.get(Constant.PROFILE_SESSION_NAME);
		if (passport != null)
		{
			logger.info("删除会话:" + passport.getUserId());
		}
		else
		{
			logger.info("删除会话");
		}
		modelMap.addAttribute(Constant.PROFILE_SESSION_NAME, new Object());
		modelMap.addAttribute(Constants.ClientConstants.USER_SESSION_KEY, new Object());
		ClientContextHolder.clearClientAction();
		return new ModelAndView(new RedirectView("/", true));
	}
}
